package cn.yx.framework.system;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Formatter;
import java.util.Locale;
import java.util.Scanner;

/**
 * Created by Administrator on 2017/3/27.
 */
public class SystemUtil {

    /**
     * 获取服务器IP和MAC地址
     *
     * @return
     * @throws Exception
     */
    public static String[] getIpMac() throws Exception {
        String[] ipMac = new String[2];
        InetAddress address = InetAddress.getLocalHost();
        NetworkInterface ni = NetworkInterface.getByInetAddress(address);
        ni.getInetAddresses().nextElement().getAddress();
        byte[] mac = ni.getHardwareAddress();
        String sIP = address.getHostAddress();
        String sMAC = "";
        Formatter formatter = new Formatter();
        for (int i = 0; i < mac.length; i++) {
            sMAC = formatter.format(Locale.getDefault(), "%02X%s", mac[i],
                    (i < mac.length - 1) ? "-" : "").toString();

        }
        ipMac[0] = sIP;
        ipMac[1] = sMAC;
        return ipMac;
    }

    /**
     * 获取服务器硬盘序列号
     * @return
     * @throws Exception
     */
    public static String getCpuId() throws Exception {

        String serial = "";
        // 判断操作系统类型
        String os = System.getProperty("os.name");
        // windows的场合
        if(os.toLowerCase().startsWith("win")){
            long start = System.currentTimeMillis();
            Process process = Runtime.getRuntime().exec(
                    new String[]{"wmic", "cpu", "get", "ProcessorId"});
            process.getOutputStream().close();
            Scanner sc = new Scanner(process.getInputStream());
            String property = sc.next();
            serial = sc.next();
            System.out.println(property + ": " + serial);
            System.out.println("time:" + (System.currentTimeMillis() - start));

        } else {
            String[] str = {"/bin/sh","-c","dmidecode -t processor | grep 'ID'"};
            Process process = Runtime.getRuntime().exec(str);
            process.waitFor();

            InputStream is = process.getInputStream();
            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader br = new BufferedReader(isr);
            String line = null;
            StringBuilder sb = new StringBuilder();
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
            is.close();
            isr.close();
            br.close();
            serial = sb.toString();
            // 去除空格
            serial = serial.replaceAll(" ","");
            // 去除ID:
            serial = serial.replaceAll("ID:","");
        }
        return serial;
    }
}
